<template>
  <by-dialog
      :modelValue="modelValue"
      watch-back
      title="发现新版本"
      :content="`发现新版本${appUpdateInfo.versionName}，是否更新？`"
      @confirm="handleUpDate"
      @cancel="$emit('update:modelValue',false)"
  />
</template>

<script setup lang="ts">
import { getLatestVersion } from '@/common/api'
import { toast } from '@/common/util'
import { doUpdateVersion, getVersion } from '@/common/plus'
import type { AnyObject } from '@/common/types'

interface IProps{
  modelValue: boolean
  showTip: boolean
}

const props = withDefaults(defineProps<IProps>(), {
  modelValue: false,
  showTip: false
})

const $emit = defineEmits(['update:modelValue', 'getVersion'])

const versionInfo = shallowRef<AnyObject>({})
async function handleGetVersion() {
  versionInfo.value = await getVersion()
  $emit('getVersion', 'v' + versionInfo.value.version)
}
handleGetVersion()

const appUpdateInfo = shallowRef<AnyObject>({})
async function handleNewGetVersion() {
  const res = await getLatestVersion({
    versionCode: versionInfo.value.versionCode
  })
  const { data } = res
  if (data) {
    appUpdateInfo.value = data
    $emit('update:modelValue', true)
  } else if (props.showTip) {
    toast('已是最新版本')
  }
}

defineExpose({
  handleNewGetVersion
})

function handleUpDate() {
  toast('已开始下载')
  doUpdateVersion(appUpdateInfo.value.downloadUrl)
}
</script>

<style scoped lang="scss">

</style>
